import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-16
 * Time: 8:17
 */
public class UdpEchoSever {
    private DatagramSocket socket = null;
    public UdpEchoSever(int port) throws SocketException {
        socket = new DatagramSocket(port);  //打开网卡文件， 并且指令服务器端口
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){ //服务器7*24h工作， 一直循环向客户端取请求并且处理
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //把读取到的二进制数据构造成字符串(结构化数据)
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //2.根据请求， 构造响应数据包
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length
            , requestPacket.getSocketAddress()); //包含目的IP和目的端口
            //3.发送返回数据包
            socket.send(responsePacket);
            //4.打印日志
            System.out.printf("[%s:%d] req:%s, resp:%s\n", requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoSever udpEchoSever = new UdpEchoSever(9090);
        udpEchoSever.start();
    }
}
